package com.xx.tools.controller.goodPerson;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import com.xx.account.domain.bo.GoodPersonBo;
import com.xx.account.domain.vo.GoodPersonVo;
import com.xx.tools.dto.goodPerson.GoodPersonJsonToBean;
import com.xx.tools.dto.goodPerson.Options;
import com.xx.common.annotation.Anonymous;
import com.xx.common.core.controller.BaseController;
import com.xx.common.core.page.TableDataInfo;
import com.xx.common.utils.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 工具Controller
 *
 * @author ruoyi
 * @date 2024-09-28
 */
@RestController
@RequestMapping("/account/goodPerson")
public class GoodPersonController extends BaseController {

    private final String URL = "http://vote.news.cn/api/poll/voters.do?id=5006&callback=jsonp_3ac082b0e41ec4";

    private GoodPersonJsonToBean getEntity() {
        // 远程调用中国好人榜接口
        HttpResponse response = HttpUtil.createRequest(Method.GET, URL).timeout(5000).execute();
        // 去掉返回数据前面的jsonp前缀和最后一个字符
        String body = response.body();
        body = response.body().substring(body.indexOf('{'), body.length() - 1);

        return JSONUtil.toBean(body, GoodPersonJsonToBean.class);
    }

    @GetMapping("/goodPersonProvinceList")
    public TableDataInfo goodPersonProvinceList() {
        startPage();
        try {
            GoodPersonJsonToBean goodPersonVo = getEntity();
            // 格式化json数据为对应的List列表
            List<Options> options = goodPersonVo.getData().getOptions();
            Set<String> provinceSet = new HashSet<>();
            for (Options option : options) {
                provinceSet.add(option.getProvince());
            }

            return getDataTable(new ArrayList<>(provinceSet));
        } catch (Exception e) {
            throw new RuntimeException("活动参数错误，请联系管理员解决");
        }
    }

    @GetMapping("/goodPersonCategoryList")
    public TableDataInfo goodPersonCategoryList() {
        startPage();
        try {
            GoodPersonJsonToBean goodPersonVo = getEntity();
            // 格式化json数据为对应的List列表
            List<Options> options = goodPersonVo.getData().getOptions();
            Set<String> provinceSet = new HashSet<>();
            for (Options option : options) {
                provinceSet.add(option.getCategory());
            }
            return getDataTable(new ArrayList<>(provinceSet));
        } catch (Exception e) {
            throw new RuntimeException("活动参数错误，请联系管理员解决");
        }
    }


    @GetMapping("/goodPersonList")
    public TableDataInfo goodPersonList(GoodPersonBo goodPersonBo) {
        startPage();
        String province = goodPersonBo.getProvince(); // 地区
        String category = goodPersonBo.getCategory(); // 类别

        List<GoodPersonVo> goodPersonVoList = new ArrayList<>();

        try {
            GoodPersonJsonToBean goodPersonVo = getEntity();

            // 格式化json数据为对应的List列表
            List<Options> options = goodPersonVo.getData().getOptions();

            // 判断是否有查询条件
            if (StringUtils.isNotEmpty(province) || StringUtils.isNotEmpty(category)) {
                // 条件过滤（同时支持 province 和 category 筛选）
                for (Options option : options) {
                    boolean matchProvince = StringUtils.isEmpty(province) || province.equals(option.getProvince());
                    boolean matchCategory = StringUtils.isEmpty(category) || category.equals(option.getCategory());

                    if (matchProvince && matchCategory) {
                        GoodPersonVo vo = new GoodPersonVo();
                        vo.setCount(option.getCount());
                        vo.setTitle(option.getTitle());
                        vo.setProvince(option.getProvince());
                        vo.setCategory(option.getCategory()); // 设置 category
                        goodPersonVoList.add(vo);
                    }
                }
            } else {
                // 条件过滤
                for (Options option : options) {
                    GoodPersonVo vo = new GoodPersonVo();
                    vo.setCount(option.getCount());
                    vo.setTitle(option.getTitle());
                    vo.setProvince(option.getProvince());
                    vo.setCategory(option.getCategory());
                    goodPersonVoList.add(vo);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("活动参数错误，请联系管理员解决");
        }

        goodPersonVoList.sort(Comparator.comparing(GoodPersonVo::getCount).reversed());

        return getDataTable(goodPersonVoList);
    }


    @Anonymous
    @GetMapping("/get-ip")
    public String getClientIp(HttpServletRequest request) {
        // 1. 直接获取客户端 IP（可能被代理服务器修改）
        String ip = request.getHeader("X-Forwarded-For");

        // 2. 如果 X-Forwarded-For 不存在，则使用 REMOTE_ADDR
        if (ip == null || ip.isEmpty()) {
            ip = request.getRemoteAddr();
        }

        // 处理多个 IP 的情况（例如多层代理）
        if (ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }

        System.out.println("客户端 IP: " + ip);

        return "当前访问 IP 为: " + ip;
    }

}
